<template>
  <div class="app-container">
    <el-form inline>
      <el-form-item>
        <el-input v-model="phone" clearable placeholder="手机号" />
      </el-form-item>

      <el-button type="primary" icon="el-icon-search" @click="search"
        >查询</el-button
      >
    </el-form>

    <el-table border stripe v-loading="listLoading" :data="usersList">
      <!-- <el-table-column type="selection" width="55" /> -->
      <el-table-column type="index" label="序号" width="80" align="center" />
      <el-table-column prop="phone" label="用户名" width="150" />
      <el-table-column prop="vip" label="VIP等级" />
      <el-table-column prop="integral" label="积分" width="180" />
      <el-table-column prop="address" label="地址" />
      <el-table-column label="操作" width="230" align="center">
        <template slot-scope="{ row }">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-edit"
            title="修改用户"
            @click="showUpdateUser(row)"
          >
          </el-button>
          <el-popconfirm
            :title="`确定删除 ${row.phone} 用户吗?`"
            @onConfirm="removeUser(row.id)"
          >
            <el-button
              style="margin-left: 10px"
              slot="reference"
              type="danger"
              size="mini"
              icon="el-icon-delete"
              title="删除用户"
            >
            </el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      :current-page="page"
      :total="total"
      :page-size="limit"
      :page-sizes="[3, 10, 20, 30, 40, 50, 100]"
      style="padding: 20px 0; text-align: center"
      layout="prev, pager, next, jumper, ->, sizes, total"
      @current-change="getUsers"
      @size-change="handleSizeChange"
    />

    <el-dialog
      :title="userInfo.id ? '修改用户' : '添加用户'"
      :visible.sync="dialogUserVisible"
    >
      <el-form
        ref="userForm"
        :model="userInfo"
        :rules="userRules"
        label-width="120px"
      >
        <el-form-item label="用户名" prop="username">
          <span>{{ userInfo.phone }}</span>
        </el-form-item>
        <el-form-item label="Vip等级">
          <el-input v-model="userInfo.vip" />
        </el-form-item>
        <el-form-item label="积分">
          <el-input v-model="userInfo.integral" />
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="userInfo.address" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button :loading="loading" type="primary" @click="addOrUpdate"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import cloneDeep from "lodash/cloneDeep";

export default {
  name: "AclUserList",

  data() {
    return {
      listLoading: false, // 是否显示列表加载的提示
      usersList: [], // 当前页的用户列表
      phone: "",
      page: 1, // 当前页码
      limit: 3, // 每页数量
      total: 0, // 总数量
      userInfo: {}, // 当前要操作的user
      dialogUserVisible: false, // 是否显示用户添加/修改的dialog
      userRules: {
        // 用户添加/修改表单的校验规则
        username: [
          { required: true, message: "用户名必须输入" },
          { min: 4, message: "用户名不能小于4位" },
        ],
        password: [{ required: true, validator: this.validatePassword }],
      },
      loading: false, // 是否正在提交请求中
      dialogRoleVisible: false, // 是否显示角色Dialog
    };
  },

  //发请求一般情况下，我们都是在mounted去发，但是也可以在created内部去发
  created() {
    this.getUserByPage();
  },

  methods: {
    search() {
      console.log("-+++++++++++");
      if (this.phone == "") {
        this.getUserByPage();
      } else {
        this.getByPhone();
      }
    },

    async getUserByPage() {
      let res = await this.$API.user.reqGetUsersByPage(this.page, this.limit);
      if (res.code == "200") {
        this.usersList = res.data.records;
        this.total = res.data.total;
      }
    },

    //根据手机号查询用户（分页）
    async getByPhone() {
      let res = await this.$API.user.reqGetUsersPageByPhone(
        this.page,
        this.limit,
        this.phone
      );
      if (res.code == "200") {
        this.usersList = res.data.records;
        this.total = res.data.total;
      }
    },

    /* 
    显示指定角色的界面
    */
    showAssignRole(user) {
      this.user = user;
      this.dialogRoleVisible = true;
      // this.getRoles();
    },

    /* 
    重置用户角色的数据
    */
    resetRoleData() {
      this.dialogRoleVisible = false;
      this.allRoles = [];
      this.userRoleIds = [];
    },

    /* 
    自定义密码校验
    */
    validatePassword(rule, value, callback) {
      if (!value) {
        callback("密码必须输入");
      } else if (!value || value.length < 6) {
        callback("密码不能小于6位");
      } else {
        callback();
      }
    },
    /* 
    根据输入进行搜索
    */
    // search() {
    //   this.searchObj = { ...this.tempSearchObj };
    //   // this.getUsers();
    // },

    /* 
    显示添加用户的界面
    */
    showAddUser() {
      this.user = {};
      this.dialogUserVisible = true;

      this.$nextTick(() => this.$refs.userForm.clearValidate());
    },

    /* 
    删除所有选中的用户
    */
    revomveUsers() {
      // this.$confirm("确定删除吗?")
      //   .then(async () => {
      //     await this.$API.user.removeUsers(this.selectedIds);
      //     this.$message.success("删除成功");
      //     this.getUsers();
      //   })
      //   .catch(() => {
      //     this.$message.info("取消删除");
      //   });
    },

    /* 
    列表选中状态发生改变的监听回调
    */
    handleSelectionChange(selection) {
      this.selectedIds = selection.map((item) => item.id);
    },

    /* 
    显示更新用户的界面
    */
    showUpdateUser(user) {
      this.user = cloneDeep(user);
      this.dialogUserVisible = true;
    },

    /* 
    删除某个用户
    */
    async removeUser(id) {
      // await this.$API.user.removeById(id);
      // this.$message.success("删除成功");
      // this.getUsers(this.users.length === 1 ? this.page - 1 : this.page);
    },

    /* 
    获取分页列表
    */
    async getUsers(page = 1) {
      // this.page = page;
      // const { limit, searchObj } = this;
      // this.listLoading = true;
      // const result = await this.$API.user.getPageList(page, limit, searchObj);
      // this.listLoading = false;
      // const { items, total } = result.data;
      // this.users = items.filter((item) => item.username !== "admin");
      // this.total = total - 1;
      // this.selectedIds = [];
    },

    /* 
    处理pageSize发生改变的监听回调
    */
    handleSizeChange(pageSize) {
      this.limit = pageSize;
      // this.getUsers();
    },

    /* 
    取消用户的保存或更新
    */
    cancel() {
      this.dialogUserVisible = false;
      this.user = {};
    },

    /* 
    保存或者更新用户
    */
    addOrUpdate() {
      // this.$refs.userForm.validate((valid) => {
      //   if (valid) {
      //     const { user } = this;
      //     this.loading = true;
      //     this.$API.user[user.id ? "update" : "add"](user).then((result) => {
      //       this.loading = false;
      //       this.$message.success("保存成功!");
      //       this.getUsers(user.id ? this.page : 1);
      //       this.user = {};
      //       this.dialogUserVisible = false;
      //     });
      //   }
      // });
    },
  },
};
</script>
